import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RequestSender extends JPanel implements ActionListener, Runnable {
	
	public static int state = 0;
	String url = "";
	
	protected Panel panel;
	protected JTextArea input, response;
	protected Button start, stop;

	public RequestSender () {
		super(new GridBagLayout());
		
		input = new JTextArea(1, 50);
		
		panel = new Panel();
		start = new Button("Start");
		start.addActionListener(this);
		panel.add(start);
		stop = new Button("Stop");
		stop.addActionListener(this);
		panel.add(stop);
		
		response = new JTextArea(15, 50);
		response.setEditable(false);
		JScrollPane responseScrollPane = new JScrollPane(response);
		
		GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;
		
		add(input, c);
		add(panel, c);
		add(responseScrollPane, c);
		
		JFrame frame = new JFrame("Request Sender");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(this);
        frame.pack();
		frame.setSize(600,350);
		frame.setLocation(200,100);
		frame.setResizable(false);
        frame.setVisible(true);
	}
	
	public void run () {
		while (true) {
			if(state ==1 ) {
				try{	
					Thread.sleep(500);
					response.append(sendRequest() + "\n");
				}
				catch (Exception e) {
					response.append(e.toString() + "\n");
				}
			}
		}
	}
	
	public String sendRequest () {
		String response = new String();
		try {
			URL targetURL = new URL(url);
			URLConnection connection = targetURL.openConnection();
			
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String inputLine;
			while ((inputLine = in.readLine()) != null)
				response = inputLine;
			in.close();
		}
		catch(Exception e) {
			response = e.toString();
		}
				
		try {
			FileWriter fstream = new FileWriter("sample.log", true);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(response + "\n");
			out.close();
		}
		catch (Exception e) {
		}
		
		return response;
	}
	
	public void actionPerformed(ActionEvent evt) {
		if (evt.getSource() == start) {
			state = 1;
			url = input.getText();
		}
		if (evt.getSource() == stop) {
			state = 0;
		}
	}

	
	public static void main (String[] args) {
		RequestSender rs = new RequestSender();
		new Thread(rs).start();
	}

}